package cn.yuxiaoyuan.user.controller;

import cn.yuxiaoyuan.annotation.PreAuthorize;
import cn.yuxiaoyuan.user.domain.User;
import cn.yuxiaoyuan.user.query.UserQuery;
import cn.yuxiaoyuan.user.service.UserService;
import cn.yuxiaoyuan.utils.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api("user相关的接口")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PreAuthorize(sn = "user:findById",name = "用户根据id查询",descs = "用户根据id查询")
    @ApiOperation("根基id查询用户信息")
    @GetMapping("/{id}")
    public R findById(@PathVariable("id")Long id){
        return R.ok(userService.findById(id));
    }

    @PreAuthorize(sn = "user:findAll",name = "用户查询全部",descs = "用户查询全部")
    @GetMapping
    public R findAll(){
        return R.ok(userService.findAll());
    }

    @PreAuthorize(sn = "user:deleteById",name = "用户根据id删除",descs = "用户根据id删除")
    @DeleteMapping("/{id}")
    public R deleteById(@PathVariable("id")Long id){
        userService.deleteById(id);
        return R.ok();
    }

    @PreAuthorize(sn = "user:batchDelete",name = "用户删除全部",descs = "用户删除全部")
    @PostMapping("/deleteAll")
    public R batchDelete(@RequestBody List<Long> ids){
        userService.batchDelete(ids);
        return R.ok();
    }

    @PreAuthorize(sn = "user:add",name = "用户添加和修改",descs = "用户添加和修改")
    @ApiOperation("添加和修改")
    @PostMapping
    public R add(@RequestBody User user){
        if(user.getId() == null){
            userService.add(user);
        }else {
            userService.update(user);
        }
        return R.ok();
    }

    @PreAuthorize(sn = "user:getPage",name = "用户分页查询",descs = "用户分页查询")
    @PostMapping("/page")
    public R queryPage(@RequestBody UserQuery query){
        //开启分页数据
        PageHelper.startPage(query.getPage(),query.getSize());
        List<User> users = userService.queryPage(query);
        //接收分页数据
        PageInfo<User> pageInfo = new PageInfo<>(users);

        System.out.println("总页数："+pageInfo.getPages());
        System.out.println("总条数："+pageInfo.getTotal());

        return R.ok(pageInfo);
    }
}
